package com.example.springboot_03_get_post.controller;

import com.alibaba.fastjson.JSON;
import com.example.springboot_03_get_post.po.BaseReqDo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Map;

@RestController
@RequestMapping(path = "/get")
public class ParamGetController {
    /**
     * HttpServletRequest
     * @param request
     * @return
     */
    @GetMapping("/req1")
    public String requestParam(HttpServletRequest request){
        Map<String, String[]> parameterMap = request.getParameterMap();
        return JSON.toJSONString(parameterMap);
    }

    @GetMapping(path = "req2")
    public String requestParam2() {
        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String name = request.getParameter("name");
        return "param Name=" + name;
    }

    /**
     * 方法参数
     * @param name
     * @param age
     * @return
     */
    @GetMapping(path = "arg")
    public String argParam(String name, Integer age) {
        return "name: " + name + " age: " + age;
    }

    /**
     * @RequestParam 请求参数
     */
    @GetMapping(path = "ano")
    public String anoParam(@RequestParam(name = "name") String uname,
                           @RequestParam(name = "age", required = false) Integer age,
                           @RequestParam(name = "uids", required = false) Integer[] uids) {
        return "name: " + uname + " age: " + age + " uids: " + (uids != null ? Arrays.asList(uids) : "null");
    }

    /**
     * PathVariable
     */
    @GetMapping(path = "url/{name}/{index}")
    public String urlParam(@PathVariable(name = "name") String name,
                           @PathVariable(name = "index", required = false) Integer index) {
        return "name: " + name + " index: " + index;
    }

    @GetMapping(path = "bean")
    public String beanParam(BaseReqDo req) {
        return req.toString();
    }

}
